<template>
	<picker @change="bindPickerChange" @columnchange="columnchange" :range="array" range-key="name" :value="value" mode="multiSelector">
		<slot></slot>
	</picker>
</template>

<script>
	import AllAddress from './data.js'
	let selectVal = ['','','']	
	export default {
		data() {
			return{
				value: [0,0,0],
				array: [],
				index: 0,
				regionList:'',//区域数据
			}
		},
		created() {
			this.getRegion()
		},
		methods:{
			//获取区域
			async getRegion() {
				var that = this
				var that = this
				var res = await this.$apis.getRegion();
				if(res){
					this.regionList = that.$toTreeData.toTreeData(
					  res.data,
					  'code',
					  'parentcode'
					);
					this.initSelect()
				}				
			},
			// 初始化地址选项
			initSelect() {
				this.updateSourceDate() // 更新源数据
				this.updateAddressDate() // 更新结果数据
				this.$forceUpdate()  // 触发双向绑定
			},
			// 地址控件改变控件
			columnchange(d) {
				this.updateSelectIndex(d.detail.column, d.detail.value) // 更新选择索引
				.updateSourceDate() // 更新源数据
				this.updateAddressDate() // 更新结果数据
				this.$forceUpdate()  // 触发双向绑定
			},			
			/** * 更新源数据 * */
			updateSourceDate() {
				var that = this;
				this.array = []
				//省
				this.array[0] = this.regionList.map(item => {
					return {
						name: item.name,
						code: item.code
					}				
				})
				//市
				this.array[1] = this.regionList[this.value[0]].children.map(item => {
					return {
						name: item.name,
						code: item.code
					}					
				})
				//区
				this.array[2] = that.regionList[this.value[0]].children[this.value[1]].children.map(item => {
					return {
						name: item.name,
						code: item.code
					}					
				})
				return this
			},			
			/** * 更新索引 * */
			updateSelectIndex(column, value){
				let arr = JSON.parse(JSON.stringify(this.value))
				arr[column] = value
				if(column === 0 ) {
					arr[1] = 0
					arr[2] = 0
				}
				if(column === 1 ) {
					arr[2] = 0
				}
				this.value = arr
				return this
			},		
			/** * 更新结果数据  * */
			async updateAddressDate() {
				var that = this
				selectVal[0] = that.array[0][this.value[0]].name
				selectVal[1] = that.array[1][this.value[1]].name 
				selectVal[2] = that.array[2][this.value[2]].name
				return this
			},			
			/*** 点击确定 * */
			bindPickerChange(e) {
				console.log(e)
				this.$emit('change', {
					index: this.value,
					data: selectVal
				})
				return this
			}
			
		}
	}
</script>

<style>
</style>
